package com.aiguigu.gulimall.cart.service.impl;

import com.aiguigu.gulimall.cart.feign.ProductFeignService;
import com.aiguigu.gulimall.cart.interceptor.CartInterceptor;
import com.aiguigu.gulimall.cart.service.CartService;
import com.aiguigu.gulimall.cart.vo.Cart;
import com.aiguigu.gulimall.cart.vo.CartItem;
import com.aiguigu.gulimall.cart.vo.SkuInfoVo;
import com.aiguigu.gulimall.cart.vo.UserInfoTo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author: charls
 * @Description:TODO
 * @Date: 2023/05/24/ 17:02
 * @Version: 1.0
 */

@Slf4j
@Service("cartService")
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX="gulimall:cart:";

    /**
     * 将某个商品添加到购物车
     * @param skuId
     * @param num
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        // 拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps=getCartOps();

        // 判断redis是否有该商品的信息
        String res = (String) cartOps.get(skuId.toString());

        // 如果没有就添加数据
        if (StringUtils.isEmpty(res)){
            // 2.商品添加到购物车
            CartItem cartItem=new CartItem();

            // 开启第一个异步任务
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                // 1.远程查询当前要添加的商品的信息
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });

                // 查出来的数据要判断是否为空
                if (!StringUtils.isEmpty(data)){
                    cartItem.setSkuId(data.getSkuId());
                    cartItem.setTitle(data.getSkuTitle());
                    cartItem.setImage(data.getSkuDefaultImg());
                    cartItem.setCheck(true);
                    cartItem.setPrice(data.getPrice());
                    cartItem.setCount(num);
                }
            }, executor);

            // 开启第二个异步任务
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                // 2.远程查询sku的组合信息
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();

            // 由 JSON.toJSONString(cartItem) 改为 JSON.toJSONString(cartItem, SerializerFeature.IgnoreErrorGetter)
            String s = JSON.toJSONString(cartItem, SerializerFeature.IgnoreErrorGetter);

            cartOps.put(skuId.toString(),s);

            return cartItem;
        }else {
            // 购物车有此商品，修改数量即可
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            if (!StringUtils.isEmpty(cartItem)){
                cartItem.setCount(cartItem.getCount()+num);
            }

            // 修改redis的数据
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));

            return cartItem;
        }
    }

    /**
     * 获取购物车中某个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        // 拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String redisValue = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(redisValue, CartItem.class);

        return cartItem;
    }

    /**
     * 获取用户登录或者未登录购物车里所有的数据
     * @return
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {

        Cart cart=new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        if (userInfoTo.getUserId()!=null){
            // 登录状态下
            String cartKey=CART_PREFIX+userInfoTo.getUserId();
            // 临时购物车的键
            String tempCartKey=CART_PREFIX + userInfoTo.getUserKey();
            // 如果临时购物车的数据还没有进行合并【合并购物车】
            List<CartItem> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if (tempCartItems!=null){
                // 临时购物车有数据需要合并
                for (CartItem item:tempCartItems){
                    addToCart(item.getSkuId(), item.getCount());
                }
                //清除临时购物车的数据
                clearCart(tempCartKey);
            }

            // 获取登录后的购物车的数据【包含合并过来的临时购物车的数据，和登录后的购物车的数据】
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }else {
            // 没登录状态下
            String cartKey=CART_PREFIX+userInfoTo.getUserKey();
            // 获取临时购物车里面的所有购物项
            List<CartItem> cartItems=getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 获取购物车里面的数据
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        // 拿到所有的购物项
        List<Object> values = hashOps.values();
        if (values!=null&&values.size()>0){
            // 遍历每个购物项
            List<CartItem> collect = values.stream().map((obj) -> {
                String str=(String)obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 清空购物车
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer checked) {
        //查询购物车里面的商品
        CartItem cartItem = getCartItem(skuId);
        //修改商品状态
        cartItem.setCheck(checked == 1?true:false);

        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),redisValue);
    }

    /**
     * 修改购物项数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {

        //查询购物车里面的商品
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),redisValue);
    }


    /**
     * 删除购物项
     * @param skuId
     */
    @Override
    public void deleteIdCartInfo(Integer skuId) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()==null){
            return null;
        }else {
            String cartKey=CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);

            // 获取所有被选中的购物项
            List<CartItem> collect = cartItems.stream()
                    .filter(item -> item.getCheck())
                    .map(item -> {
                        R price = productFeignService.getPrice(item.getSkuId());
                        // TODO 1.更新为最新价格 --->去商品服务中查最新的价格
                        String data = (String) price.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;
                    }).collect(Collectors.toList());

            return collect;
        }
    }

    /**
     * 获取到我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //先得到当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //gulimall:cart:1
            // 用户登录了
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            // 用户没登录
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        System.out.println("准备去redis拿东西啦");
        //绑定指定的key操作Redis
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);


        return operations;
    }
}
